package com.yyw.gulimall.authserver.controller;

import com.yyw.common.constant.auth.AuthServerConstant;
import com.yyw.common.constant.common.UrlConstant;
import com.yyw.common.exception.OAuth2LoginException;
import com.yyw.gulimall.authserver.abstracts.RootOAuth2Service;
import com.yyw.gulimall.authserver.service.impl.WeiboOAuth2ServiceImpl;
import com.yyw.gulimall.authserver.utils.SpringUtil;
import com.yyw.common.to.oauth.MemberVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @Classname ThirdPartyController
 * @Description 第三方登录控制器
 * @Date 2020/12/16 8:59
 * @Created yyw
 */
@Controller
@RequestMapping("/oauth2")
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ThirdPartyController {

    RootOAuth2Service oAuth2Service = null;

    /**
     * 微博登录
     * 当用户点击了确认授权，通过微博颁发的code 换取 accessToken
     *
     * @param code
     * @return 登录成功的页面
     */
    @GetMapping("/weibo/success")
    public String weiBo(@RequestParam("code") String code, RedirectAttributes attributes, HttpSession session) {
        try {
            oAuth2Service = SpringUtil.getBean(WeiboOAuth2ServiceImpl.class);
            MemberVo vo = oAuth2Service.login(code);
            log.info("获取到用户信息:{}", vo);
            // 存放session
            session.setAttribute(AuthServerConstant.SESSION_LOGIN_USER, vo);
            return "redirect:" + UrlConstant.PRODUCT_URL;
        } catch (OAuth2LoginException e) {
            e.printStackTrace();
            attributes.addFlashAttribute("loginError", e.getMessage());
            return "redirect:" + UrlConstant.AUTH_URL + "/login";
        }
    }

    /**
     * 取消授权返回
     * @return
     */
    @GetMapping("/weibo/fail")
    public String weiBoFail() {
        return "redirect:" + UrlConstant.AUTH_URL + "/login";
    }
}
